/*
 * @FileName: [MerchantController.java]
 * 
 * @Package com.bcinfo.iccard.admin.iccard.controller
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO Technology Limited Company ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 914 $ $LastChangedDate: 2013-12-28 14:30:51 +0800 (Sat, 28 Dec 2013) $ $LastChangedBy: xug $
 * 
 * @category bcinfo-upp
 * 
 * @version 1.1
 * 
 * @author $Author: xug $
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

package com.bcinfo.iccard.admin.iccard.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bcinfo.iccard.admin.common.ModuleEnum;
import com.bcinfo.iccard.admin.controller.AbstractController;
import com.bcinfo.iccard.exception.IccardDatabaseException;
import com.bcinfo.iccard.exception.InvalidParametersException;
import com.bcinfo.iccard.exception.MerchantEncodeHasBandByOtherException;
import com.bcinfo.iccard.model.CheckReason;
import com.bcinfo.iccard.model.ComboCard;
import com.bcinfo.iccard.model.ComboCardCheckreason;
import com.bcinfo.iccard.model.ExpenseRecord;
import com.bcinfo.iccard.model.Merchant;
import com.bcinfo.iccard.model.Pos;
import com.bcinfo.iccard.service.ExpenseRecordService;
import com.bcinfo.iccard.service.MerchantService;
import com.bcinfo.iccard.service.impl.MerchantNameIsExistException;
import com.bcinfo.iccard.util.PaginationList;

/**
 * 商家管理 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * TODO 详细描述
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 *      TODO 代码使用示例
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/iccard/merchant")
public class MerchantController extends AbstractController
{
    @Autowired
    private MerchantService      merchantService;
    @Autowired
    private ExpenseRecordService expensiveRecordService;

    @RequestMapping("/toListView")
    public ModelAndView toListView()
    {
        ModelAndView modelAndView = new ModelAndView("iccard/merchant/merchant_list");
        /*
         * PaginationList<Merchant> list = null; try { list = merchantService.merchantList("", -1, -1, "", "", 10, 1); if (list != null) { modelAndView.addObject("rows", list.getRecords()); modelAndView.addObject("total", list.getTotalRecord()); System.out.println("list.getRecords():" + list.getRecords()); System.out.println("list.getTotalRecord():" + list.getTotalRecord()); } } catch (Exception e) { e.printStackTrace(); modelAndView.addObject("total", 0); handleException(e); }
         */
        return modelAndView;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(String sellerCode, String merchantCheckStatus, String merchantType,
            String beginTime, String endTime)
    {
        System.out.println("sellerCode:=="+sellerCode);
        String merchantEncode = "";
        if (StringUtils.isNotBlank(sellerCode))
        {
            String[] ss = sellerCode.split(",");
            merchantEncode = ss[0];
        }
        
        
        Map<String, Object> map = new HashMap<String, Object>();
        PaginationList<Merchant> list = null;
        if (merchantCheckStatus == null || "".equals(merchantCheckStatus))
        {
            merchantCheckStatus = "-1";
        }
        if (merchantType == null || "".equals(merchantType))
        {
            merchantType = "-1";
        }
       
        try
        {
            list = merchantService.merchantList(merchantEncode, Integer.parseInt(merchantCheckStatus), Integer
                    .parseInt(merchantType), beginTime, endTime, getPageSize(), getPage());
            if (list != null)
            {
                map.put("rows", list.getRecords());
                map.put("total", list.getTotalRecord());
            }
        }
        catch (Exception e)
        {
            map.put("total", 0);
            handleException(e);
        }

        return map;
    }

    /**
     * 转到新增页面 <br/>
     * <p>
     * Description: 转到新增页面 <br/>
     * <br/>
     * <p>
     * Author: xug<br/>
     * <p>
     * Date: 2013-12-9-下午05:37:51<br/>
     * <p>
     * 
     * @return
     * 
     */
    @RequestMapping("/toAddView")
    public ModelAndView toAddView()
    {
        ModelAndView mv = new ModelAndView("iccard/merchant/merchant_add");
        mv.addObject("nextaction", "add");
        mv.addObject("formtitle", "新增");
        return mv;

    }

    @RequestMapping("/toEditView")
    public ModelAndView toEditView(Long merchantId)
    {
        ModelAndView mv = new ModelAndView("iccard/merchant/merchant_add");
        Merchant merchant = null;

        try
        {
            merchant = merchantService.load(merchantId);
        }
        catch (IccardDatabaseException e)
        {
            handleException(e);
        }

        request.setAttribute("merchant", merchant);

        mv.addObject("nextaction", "update");
        mv.addObject("formtitle", "编辑");

        return mv;

    }

    /**
     * 
     * 创建商家信息 <br/>
     * <p>
     * Description: TODO(创建商家信息) <br/>
     * <p>
     * Author: Administrator<br/>
     * <p>
     * Date: 2013-12-11-上午10:24:13<br/>
     * <p>
     * 
     * @param merchant
     * @return
     * 
     */
    @RequestMapping("/add")
    @ResponseBody
    public Map<String, String> add(Merchant merchant)
    {
        // if (!this.hasPermission(ModuleEnum.Merchant.add))// 没有权限
        // {
        // _log.error("权限不足");
        // return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        // }
        System.out.println(merchant.toString());
        Map<String, String> map = null;

        merchant.setMerchantCheckStatus(2);// 待审核
        merchant.setMerchantStatus(1);// 正常
        merchant.setBillingStatus(1);// 允许结算
        merchant.setIsDelete(true);// 可以删除

        System.out.println("MerchantController add........................................");
        System.out.println(merchant.toString());

        try
        {
            merchantService.add(merchant);
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Merchant.add, "merchant=" + merchant.toString() + "|desc=新增商家成功");
        }
        catch (MerchantEncodeHasBandByOtherException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "商家编码已存在，新增商家失败。");
            addLog(ModuleEnum.Merchant.add, "商家编码已存在，新增商家失败。");
        }
        catch (IccardDatabaseException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "数据库错误");
            addLog(ModuleEnum.Merchant.add, "数据库错误");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "新增商家失败");
            addLog(ModuleEnum.ComboCard.add, "新增商家失败");
        }

        return map;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Map<String, String> update(Merchant merchant)
    {
        // if (!this.hasPermission(ModuleEnum.Merchant.update))// 没有权限
        // {
        // _log.error("权限不足");
        // return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        // }
        Map<String, String> map = null;

       // String oldMerchantEncode = request.getParameter("oldMerchantEncode");
        String oldRechargeableCardDiscountRate = request.getParameter("oldRechargeableCardDiscountRate");
        //String oldPosIdStr = request.getParameter("oldPosIdStr");

      /*  String newPosIdStr = "";
        List<Pos> list = new ArrayList<Pos>();
        list = merchant.getPoslists();
        if (list.size() > 0)
        {
            for (Pos pos : list)
            {
                newPosIdStr += pos.getPosCode() + ",";
            }
        }*/

       /* if (oldMerchantEncode != null && !oldMerchantEncode.equals(merchant.getMerchantEncode()))
        {
            merchant.setMerchantCheckStatus(2);// 待审核,关键信息修改时需要审核
        }*/
        if (oldRechargeableCardDiscountRate != null
                && !oldRechargeableCardDiscountRate.equals(merchant.getRechargeableCardDiscountRate()))
        {
            merchant.setMerchantCheckStatus(2);// 待审核,关键信息修改时需要审核
        }
        /*if (oldPosIdStr != null && !oldPosIdStr.equals(newPosIdStr))
        {
            merchant.setMerchantCheckStatus(2);// 待审核,关键信息修改时需要审核
        }*/

        System.out.println(merchant.toString());
       // System.out.println(newPosIdStr);

        if (merchant == null || merchant.getMerchantId() <= 0)
        {
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                    "InvalidParameterException", "编辑失败");
        }

        try
        {
            merchantService.update(merchant);
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Merchant.update, "merchant=" + merchant.toString() + "|desc=商家编辑成功");
        }
        catch (MerchantEncodeHasBandByOtherException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "商家编码已经存在");
            addLog(ModuleEnum.Merchant.update, "商家编码已经存在");
        }
        catch (IccardDatabaseException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "数据库错误");
            addLog(ModuleEnum.Merchant.update, "数据库错误");
        }
        catch (MerchantNameIsExistException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "商家名称已经存在");
            addLog(ModuleEnum.Merchant.update, "商家名称已经存在");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Merchant.update, "编辑失败");
        }

        return map;
    }

    @RequestMapping("/toAuditView")
    public ModelAndView toAuditView()
    {

        ModelAndView mv = new ModelAndView("iccard/merchant/merchant_audit");
        // if (!this.hasPermission(ModuleEnum.Merchant.audit))// 没有权限
        // {
        // _log.error("权限不足");
        // return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        // }
        try
        {
            Merchant merchant = merchantService.loadAuditInfo(Long.parseLong((String) request.getParameter("merchantId")));
            mv.addObject("merchant", merchant);
            CheckReason checkReason = merchantService.loadRecentlyCheckReason(Long.parseLong((String) request
                    .getParameter("merchantId")));
            mv.addObject("checkReason", checkReason);
        }
        catch (IccardDatabaseException e)
        {
            handleException(e);
        }

        return mv;
    }

    @RequestMapping("/audit")
    @ResponseBody
    public Map<String, String> audit(long merchantId, int status, String msg)
    {
        // if (!this.hasPermission(ModuleEnum.Merchant.audit))// 没有权限
        // {
        // _log.error("权限不足");
        // return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        // }

        Map<String, String> map = null;
        if (merchantId <= 0 && status < 0 && status > 1)// merchant_check_status 0：审核未通过 1：审核已通过 2：待审核
        {
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                    "InvalidParameterException", "审核失败");
        }
        try
        {
            merchantService.audit(merchantId, status, msg, getOperatorId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Merchant.audit, "merchantId=" + merchantId + "|desc=审核商家成功");
        }
        catch (IccardDatabaseException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "数据库错误");
            addLog(ModuleEnum.Merchant.audit, "数据库错误");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Merchant.audit, "审核失败");
        }
        return map;
    }

    @RequestMapping("/load")
    @ResponseBody
    public ModelAndView load(Long merchantId)
    {
        /*
         * if (!this.hasPermission(ModuleEnum.Merchant.view))// 没有权限 { _log.error("权限不足"); return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足"); }
         */
        ModelAndView modelAndView = new ModelAndView("iccard/merchant/merchant_view");
        Merchant merchant = null;

        try
        {
            merchant = merchantService.load(merchantId);
        }
        catch (IccardDatabaseException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            handleException(e);
        }

        request.setAttribute("merchant", merchant);
        return modelAndView;
    }

    @RequestMapping("/setStatus")
    @ResponseBody
    public Map<String, String> setStatus(Long merchantId, int merchantStatus)
    {
        Map<String, String> map = null;
        /*
         * if (!this.hasPermission(ModuleEnum.Merchant.setStatus))// 没有权限 { _log.error("权限不足"); return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足"); }
         */
        String string = "";

        Merchant merchant = new Merchant();
        merchant.setMerchantId(merchantId);
        merchant.setMerchantStatus(merchantStatus);

        if (merchant.getMerchantStatus() == 0)
        {
            string = "冻结";
        }
        else
        {
            string = "解冻";
        }

        try
        {
            merchantService.setStatus(merchant.getMerchantId(), merchant.getMerchantStatus());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Merchant.setStatus, "merchantId=" + merchant.getMerchantId() + "|desc=" + string + "商家成功");
        }
        catch (IccardDatabaseException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "数据库错误");
            addLog(ModuleEnum.Merchant.setStatus, "数据库错误");
        }
        catch (InvalidParametersException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                    "InvalidParameterException", "失败");
            addLog(ModuleEnum.Merchant.setStatus, "参数错误");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Merchant.setStatus, string + "商家失败");
        }
        return map;
    }

    /**
     * 
     * 商家详情 <br/>
     * <p>
     * Description: TODO(详细描述) <br/>
     * <p>
     * Author: xug<br/>
     * <p>
     * Date: 2013-12-20-上午11:03:54<br/>
     * <p>
     * 
     * @return
     * 
     */
    @RequestMapping("/toInfoView")
    public ModelAndView toInfoView()
    {

        ModelAndView mv = new ModelAndView("iccard/merchant/merchant_info");
        /*
         * if (!this.hasPermission(ModuleEnum.Merchant.view))// 没有权限 { _log.error("权限不足"); return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足"); }
         */
        try
        {
            Merchant merchant = merchantService.load(Long.parseLong((String) request.getParameter("merchantId")));
            mv.addObject("merchant", merchant);
            CheckReason checkReason = merchantService.loadRecentlyCheckReason(Long.parseLong((String) request
                    .getParameter("merchantId")));
            mv.addObject("checkReason", checkReason);
        }
        catch (IccardDatabaseException e)
        {
            handleException(e);
        }

        return mv;
    }

    /**
     * 
     * 删除<br/>
     * <p>
     * Description: TODO(详细描述) <br/>
     * <p>
     * Author: xug<br/>
     * <p>
     * Date: 2013-12-23-下午05:49:42<br/>
     * <p>
     * 
     * @param merchantId
     * @return
     * 
     */
    @RequestMapping("/remove")
    @ResponseBody
    public Map<String, String> remove(long merchantId)
    {
        // if (!this.hasPermission(ModuleEnum.Merchant.remove))// 没有权限
        // {
        // _log.error("权限不足");
        // return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        // }
        Map<String, String> map = null;
        if (merchantId <= 0)
        {
            return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                    "InvalidParameterException", null);
        }
        try
        {
            merchantService.delete(merchantId);
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Merchant.remove, "merchantId=" + merchantId + "|desc=删除商家成功");
        }
        catch (IccardDatabaseException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "数据库错误");
            addLog(ModuleEnum.Merchant.remove, "数据库错误");
        }
        catch (Exception e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), null);
            addLog(ModuleEnum.Merchant.remove, "删除套餐卡失败");
        }
        return map;
    }

    @RequestMapping("/toERListView")
    public ModelAndView toERListView()
    {
        ModelAndView modelAndView = new ModelAndView("iccard/merchant/merchant_ERlist");

        String merchantEncode = request.getParameter("merchantEncode");
        String merchantName = request.getParameter("merchantName");
        modelAndView.addObject("merchantEncode", merchantEncode);
        modelAndView.addObject("merchantName", merchantName);

        return modelAndView;
    }

    @RequestMapping("/expensiveRecordlist")
    @ResponseBody
    public Map<String, Object> expensiveRecordlist(String merchantEncode, String cardType, String isAccount,
            String beginTime, String endTime)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        PaginationList<ExpenseRecord> list = null;
        if (cardType == null || "".equals(cardType))
        {
            cardType = "-1";
        }
        if (isAccount == null || "".equals(isAccount))
        {
            isAccount = "-1";
        }
        try
        {
            /*
             * list = merchantService.merchantList(merchantCode, Integer.parseInt(merchantCheckStatus), Integer .parseInt(merchantType), beginTime, endTime, getPageSize(), getPage());
             */
            list = expensiveRecordService.expenseRecordList(merchantEncode, Short.valueOf(cardType), Short
                    .valueOf(isAccount), beginTime, endTime, getPageSize(), getPage());
            if (list != null)
            {
                map.put("rows", list.getRecords());
                map.put("total", list.getTotalRecord());
            }
        }
        catch (Exception e)
        {
            map.put("total", 0);
            handleException(e);
        }

        return map;
    }
    
    
    @RequestMapping("/checkMerchantName")
    @ResponseBody
    public boolean checkMerchantName(String merchantName)
    {
        boolean bl = false;
        try
        { 
            int count = merchantService.checkMerchantName(merchantName);
            if(count>0){
                bl = true;
            }
        }
        catch (IccardDatabaseException e)
        {
            handleException(e);
        }
        catch (Exception e)
        {
            handleException(e);
        }
        return bl;
    }

    @RequestMapping("/checkMerchantEncode")
    @ResponseBody
    public boolean checkMerchantEncode(String merchantEncode)
    {
        boolean bl = false;
        try
        { 
            int count = merchantService.checkMerchantEncode(merchantEncode);
            if(count>0){
                bl = true;
            }
        }
        catch (IccardDatabaseException e)
        {
            handleException(e);
        }
        catch (Exception e)
        {
            handleException(e);
        }
        return bl;
    }
    
    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @return
     * 
     * @see com.bcinfo.iccard.admin.controller.AdminController#getMouduleCode()
     */
    @Override
    public String getMouduleCode()
    {
        // TODO Auto-generated method stub
        return null;
    }

}
